﻿// Please don't remove line below - it is used for code-completion for Visual Studio
/// <reference path="preview\vsdoc.js" />
/// <reference path="basic.js" />

var bbcUrl = 'http://www.bbc.co.uk/';
var bbcProgrammesUrl = bbcUrl + 'programmes/';
var ext = '.json';

var bbcTvServices = Array();
var bbcRadioServices = Array();

var RADIO_OUTLET = 1;
var TV_OUTLET = 2;

function initBBCProgrammesApi() {
    homePage();
    loadServices();
    addClearMenu();
}

function addClearMenu() {
    var cleanMenu = new MenuItem('Reset Preferences', null);
    cleanMenu.onSelect = function(id) {
    for (var i = 0; i < services.length; i++) {
            widget.setPreferenceForKey(null, services[i].key);
        }
    };
    menu.append(cleanMenu);
}

function homePage() {
    setTitle("BBC Schedules");
    menu.setRightSoftkeyLabel('', null);
    cleanMainView();
    var tvNav = new NavigationButton(null, null, 'TV');
    var radioNav = new NavigationButton(null, null, 'Radio');
    
    tvNav.addEventListener("ActionPerformed", showTv);
    radioNav.addEventListener("ActionPerformed", showRadio);
    mainView.addControl(tvNav);
    mainView.addControl(new Separator(null));
    mainView.addControl(radioNav);
}

function loadServices() {
    lookup(bbcProgrammesUrl + 'services' + ext, 'Loading Services', loadServicesCallback, null);
}

var services;

function loadServicesCallback(data) {
    services = data.services;
    for (var i = 0; i < services.length; i++) {
        if (services[i].type == 'tv') {
            bbcTvServices.push(services[i]);
        } else if (services[i].type == 'radio') {
            bbcRadioServices.push(services[i]);
        }
    }
}

function showTv(event) {
    showOutletArgs = { outlet: TV_OUTLET, title: 'TV', array: bbcTvServices };
    showOutlet();
}

function showRadio(event) {
    showOutletArgs = { outlet: RADIO_OUTLET, title: 'Radio', array: bbcRadioServices };
    showOutlet();
}

var showOutletArgs;

function showOutlet() {
    menu.setRightSoftkeyLabel('Back', homePage);
    setTitle(showOutletArgs.title);
    cleanMainView();
    for (var i = 0; i < showOutletArgs.array.length; i++) {
        var service = new NavigationButton(i, null, showOutletArgs.array[i].title);
        service.addEventListener("ActionPerformed", showChannel);
        mainView.addControl(service);
        mainView.addControl(new Separator(null));
    }
}

var showChannelArgs;

function showChannel(event) {
    if (event != null) {
        showChannelArgs = { channelId: event.source.id };
    }
    var array = null;
    switch (showOutletArgs.outlet) {
        case RADIO_OUTLET:
            array = bbcRadioServices;
            break;
        case TV_OUTLET:
            array = bbcTvServices;
            break;
    }
    if (array[showChannelArgs.channelId].outlets != null) {
        showChannelOutlet();
    } else {
        getSchedule(array[showChannelArgs.channelId].key, showChannelCallback);
    }
}

function showChannelOutlet() {
    switch (showOutletArgs.outlet) {
        case RADIO_OUTLET:
            array = bbcRadioServices;
            break;
        case TV_OUTLET:
            array = bbcTvServices;
            break;
    }
    var preference = widget.preferenceForKey(showChannelArgs.channelId);
    if (preference != null) {
        getOutletSchedule(array[showChannelArgs.channelId].key, preference, showChannelCallback);
    } else {
        cleanMainView();
        setTitle('Choose outlet for ' + array[showChannelArgs.channelId].title);
        for (var i = 0; i < array[showChannelArgs.channelId].outlets.length;  i++) {
            var service = new NavigationButton(i, null, array[showChannelArgs.channelId].outlets[i].title);
            service.addEventListener("ActionPerformed", setChannelOutletChoice);
            mainView.addControl(service);
            mainView.addControl(new Separator(null));
        }
    }
}

function setChannelOutletChoice(event){
    switch (showOutletArgs.outlet) {
        case RADIO_OUTLET:
            array = bbcRadioServices;
            break;
        case TV_OUTLET:
            array = bbcTvServices;
            break;
    }
    var preference = array[showChannelArgs.channelId].outlets[event.source.id].key;
    widget.setPreferenceForKey(preference, showChannelArgs.channelId);
    getOutletSchedule(array[showChannelArgs.channelId].key, preference, showChannelCallback);
}

var currentEvents = Array();
var addToCalendarMenuItem;

var showChannelCallbackArgs;

function showChannelCallback(data) {
    if (data != null) {
        showChannelCallbackArgs = { data: data };
    }
    menu.setRightSoftkeyLabel('Back', showOutlet);
    var outlet = showChannelCallbackArgs.data.schedule.service.outlet;
    if (outlet != null) {
        outlet = outlet.title;
        title = showChannelCallbackArgs.data.schedule.service.title + ' - ' + outlet;
    } else {
        title = showChannelCallbackArgs.data.schedule.service.title;
    }
    setTitle(title);
    cleanMainView();
    currentEvents = new Array();
    for (var i = 0; i < showChannelCallbackArgs.data.schedule.day.broadcasts.length; i++) {
        var prog = showChannelCallbackArgs.data.schedule.day.broadcasts[i].programme;
        var show = new NavigationButton(i, null, prog.display_titles.title + '-' + prog.display_titles.subtitle);
        show.addEventListener("ActionPerformed", showProgramme);
        mainView.addControl(show);
        currentEvents.push(showChannelCallbackArgs.data.schedule.day.broadcasts[i]);
        mainView.addControl(new Separator(null));
    }
}

function showProgramme(event) {
    menu.setRightSoftkeyLabel('Back', showChannelCallback);
    var broadcast = currentEvents[event.source.id];
    cleanMainView();
    setTitle(broadcast.programme.display_titles.title);
    var description = new Label(null, 'Synopsis', broadcast.programme.short_synopsis);
    mainView.addControl(description);
    //var startTime = Date.parse(broadcast.start);
    //var startLabel = new Label(null, 'Broadcast', startTime.toString());
    //mainView.addControl(startLabel);

    addToCalendarMenuItem = new MenuItem('Add to calendar', event.source.id);
    addToCalendarMenuItem.onSelect = addShowToCalendar;
    menu.append(addToCalendarMenuItem);
}

function addShowToCalendar(id) {
    try {
        var calendar = device.getServiceObject("Service.Calendar", "IDataSource");
        var st = new Date();
        st.setUTCMonth(2, 17);  // month and day specified
        st.setUTCHours(6, 00);  // 11:30 AM Blr time in UTC/GMT
        var et = new Date();
        et.setUTCMonth(2, 17);  // month and day specified
        et.setUTCHours(7, 00);  // 12:30 PM Blr time in UTC/GMT

        var item = new Object();
        item.Type = "Meeting";
        item.StartTime = st;
        item.EndTime = et;

        var criteria = new Object();
        criteria.Type = "CalendarEntry";
        criteria.Item = item;
        calendar.IDataSource.Add(criteria);
    } catch (err) { alert(err); }
}

function setTitle(title) {
    mainView.setCaption(title);
}

function cleanMainView() {
    var controlArr = mainView.getControls();
    for (var j = controlArr.length - 1; j > -1; j--) {
        mainView.removeControl(controlArr[j]);
    }
    if (addToCalendarMenuItem != null) {
        menu.remove(addToCalendarMenuItem);
        addToCalendarMenuItem = null;
    }
}

function getOutletSchedule(source, outlet, callback) {
    lookup(bbcUrl + source + '/programmes/schedules/' + outlet + ext, 'Loading Schedule', callback, null);
}

function getSchedule(source, callback) {
    lookup(bbcUrl + source + '/programmes/schedules' + ext, 'Loading Schedule', callback, null);
}

function lookup(url, loadingMessage, callback, error) {
    var ajax = new Ajax();
    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4) {
            if (ajax.status == 200) {
                var data = eval('(' + ajax.responseText + ')');
                uiManager.hideNotification();
                callback(data);
            } else {
                error(ajax.status);
            }
        }
    };
    uiManager.showNotification(null, 'wait', loadingMessage, -1);
    ajax.open("GET", url, true);
    ajax.send(null);
}